package org.elsfs.cloud.common.mybatis.ext.sql.support.condition;

import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.mybatis.ext.sql.SqlParameterManager;
import org.elsfs.cloud.common.util.lang.NamingCase;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 范围条件
 *
 */
@RequiredArgsConstructor
public class InConditionItem implements ConditionItem {

    /**
     * SQL参数管理器
     */
    protected final SqlParameterManager sqlParameterManager;
    /**
     * 左边字段名称
     */
    protected final String leftField;
    /**
     * 范围字段
     */
    protected final Collection<String> inFields;
    /**
     * 范围值
     */
    protected final Collection<?> inValues;

    /**
     * 构建SQL片段
     *
     * @return SQL片段
     */
    @Override
    public String buildSqlFragment() {
        List<String> tokens = new ArrayList<>(inFields.size() + inValues.size());


        for (String inField : this.inFields) {
            tokens.add(NamingCase.toUnderlineCase(inField));
        }
        for (Object inValue : this.inValues) {
            tokens.add(
                SqlParameterManager.buildParameterPlaceholder(
                        this.sqlParameterManager.registerParameter(inValue)
                )
            );
        }

        return this.buildSqlFragment(
            String.join(", ", tokens)
        );
    }

    /**
     * 构建SQL片段
     *
     * @param token IN部分SQL
     * @return SQL片段
     */
    protected String buildSqlFragment(String token) {
        return String.format(
            "%s IN (%s)",
            NamingCase.toUnderlineCase(this.leftField),
            token
        );
    }
}
